from typing import List, Dict, Tuple, Optional
from playwright.async_api import async_playwright
from twocaptcha import TwoCaptcha
import os
import os.path
import json
from fake_useragent import UserAgent


## Cookies
ua =  UserAgent(browsers=["Chrome"])

def get_stored_cookies(cookie_file_url: str) -> list[dict]:
    if os.path.isfile(cookie_file_url):
        with open(cookie_file_url, "r") as f:
            cookies = json.loads(f.read())
            return cookies
    else:
        return []


def set_stored_cookies(cookie_file_url: str, cookies):
    with open(cookie_file_url, "w+") as f:
        f.write(json.dumps(cookies))


def get_captcha_code(file_url: str):
    two_captcha_api_key = os.getenv("2CAPTCHA_APIKEY")
    print(f"two_captcha_api_key={two_captcha_api_key}")
    solver = TwoCaptcha(
        apiKey=two_captcha_api_key, defaultTimeout=60, pollingInterval=10
    )
    print("file_url=>", file_url)
    result = solver.normal(file_url)
    print("2captcha solver result:", result)
    return result["code"]


async def get_login_cookies(
    login_url: str,
    redirect_url: str,
    # captcha_url: str,
    user: str,
    pwd: str,
    cookie_file_url: str,
    headless: bool = True,
) -> List[dict]:
    """Authenticate using Playwright and get full browser state"""
    async with async_playwright() as p:
        browser = await p.chromium.launch(headless=headless)
        context = await browser.new_context(user_agent=ua.random)
        page = await context.new_page()
        url = f"{login_url}?from={redirect_url}"
        try:
            await page.goto(url, wait_until="networkidle", timeout=60000)
            captcha_file_url = "captcha.png"

            # captcha_page = await context.new_page()
            # await captcha_page.goto(
            #     captcha_url, wait_until="networkidle", timeout=15000
            # )
            # await captcha_page.screenshot(path=captcha_file_url)
            # await captcha_page.close()

            captcha_img = page.locator("#imgCode")
            await captcha_img.wait_for(timeout=10000)
            await captcha_img.screenshot(path=captcha_file_url)

            await page.fill('input[name="email"]', user)
            await page.fill('input[name="pwd"]', pwd)
            code = get_captcha_code(captcha_file_url)
            await page.fill('input[name="code"]', code)
            login_btn = page.locator("#denglu")
            # await login_btn.wait_for(timeout=1000)
            # print('loginbutton wait_for:', login_btn.inner_text())
            await login_btn.click()
            print("clicked login_btn...")
            await page.wait_for_url(redirect_url, timeout=60000)
            print("wait redirected")
            cookies = await context.cookies()
            set_stored_cookies(cookie_file_url, cookies)
            # logger.info(f"Authenticated. Retrieved cookies {cookies}.")
            print(f"Authenticated. Retrieved cookies {cookies}.")
            await browser.close()

            return cookies

        except Exception as e:
            await browser.close()
            # logger.error(f"Login failed: {str(e)}")
            print(f"Login failed: {str(e)}")
            raise
